package test;

import java.util.Arrays;

public class MyBitSet {
    public byte[] elem;
    public int usedSize;

    public MyBitSet() {
        this.elem = new byte[1];
    }

    public MyBitSet(int n) {
        this.elem = new byte[n / 8 + 1];
    }

    //设置某一位为一
    public void set(int val) {
        if (val < 0) {
            System.out.println("只能为无符号整数，不能为负数");
            throw new IndexOutOfBoundsException();
        }

        int arrayIndex = val / 8;
        if (arrayIndex > elem.length - 1) {
            elem = Arrays.copyOf(elem, arrayIndex + 1);
        }
        int bitIndex = val % 8;
        elem[arrayIndex] |= (1 << bitIndex);
        usedSize++;
    }

    public int getUsedSize() {
        return usedSize;
    }

    //判断当前位 是不是1
    public boolean get(int val) {
        if (val < 0) {
            System.out.println("只能为无符号整数，不能为负数");
            throw new IndexOutOfBoundsException();
        }
        int arrayIndex = val / 8;
        if (arrayIndex > elem.length - 1) {
            elem = Arrays.copyOf(elem, arrayIndex + 1);
        }
        int bitIndex = val % 8;

        if ((elem[arrayIndex] & (1 << bitIndex)) != 0) {
            return true;
        }
        return false;
    }

    //将对应位置 置位0
    public void reSet(int val) {
        if (val < 0) {
            System.out.println("只能为无符号整数，不能为负数");
            throw new IndexOutOfBoundsException();
        }
        int arrayIndex = val / 8;
        int bitIndex = val % 8;
        elem[arrayIndex] &= ~(1 << bitIndex);
        usedSize--;
    }

    public static void main(String[] args) {
        MyBitSet myBitSet = new MyBitSet(22);
        int[] array = {1, 3, 7, 4, 12, 16, 19, 13, 22, 18, 3};
        for (int i = 0; i < array.length; i++) {
            myBitSet.set(array[i]);
        }
        System.out.println(myBitSet.getUsedSize());
        System.out.println(myBitSet.get(7788));
        System.out.println(myBitSet.get(4));

        //排序 时间复杂度O(N)
        for (int i = 0; i < myBitSet.elem.length; i++) {
            for (int j = 0; j < 8; j++) {
                if ((myBitSet.elem[i] & (1 << j)) != 0) {
                    System.out.print((i * 8 + j) + " ");
                }
            }
        }
    }
}
